import { Component, Prop, Vue, Emit, Watch } from 'vue-property-decorator'
import styles from '../NewApply/ApplyDetail.less'
import sealStyle from './UpdateSeal.less'
import ImagePreview from '@/components/ImagePreview'
import DetailItem from '@/components/DetailItem'
import OptionLine from '@/components/OptionLine'
import Upload from '@/components/Upload'
import { ElForm } from 'element-ui/types/form'
import { orgLicenseTypes, IStatus } from '@/lib/sealFormat'

const formLabelWidth3: string = '48px'
const formLabelWidth4: string = '60px'
const formLabelWidth5: string = '84px'
const formLabelWidth8: string = '72px'
const fileTypes = [
  'image/jpeg',
  'image/jpg',
  'image/png',
  'image/bmp',
  'image/gif',
]
const fileSizeLimit = 10

const detailData = [
  {
    title: '用章机构基本信息',
    child: [
      {
        id: 'organizeName',
        label: '机构名称',
        content: '',
        labelWidth: formLabelWidth3,
      },
      {
        id: 'organizeTypeName',
        label: '机构类型',
        content: '',
        labelWidth: formLabelWidth8,
      },
      {
        id: 'organizeCardTypeName',
        label: '证照类型',
        content: '',
        labelWidth: formLabelWidth3,
      },
      {
        id: 'organizeCardId',
        label: '证照号码',
        content: '',
        labelWidth: formLabelWidth8,
      },
      // {
      // 	id: "organizeLevelName",
      // 	label: "行政等级",
      // 	content: "",
      // 	labelWidth: formLabelWidth3
      // }
    ],
  },
  {
    title: '经办人基本信息',
    child: [
      {
        id: 'agentName',
        label: '经办人姓名',
        content: '',
        labelWidth: formLabelWidth4,
      },
      {
        id: 'agentMobileDes',
        label: '经办人手机号',
        content: '',
        labelWidth: formLabelWidth8,
      },
      {
        id: 'agentLicenseTypeName',
        label: '经办人证件类型',
        content: '',
        labelWidth: formLabelWidth5,
      },
      {
        id: 'agentLicenseNumberDes',
        label: '经办人证件号',
        content: '',
        labelWidth: formLabelWidth8,
      },
    ],
  },
  {
    id: 'sealInfo',
    title: '申请印章信息',
    child: [
      {
        id: 'sealTypeName',
        label: '印章类别',
        content: '',
        labelWidth: formLabelWidth3,
        tips:
          '组织机构的电子法定名称章需要上级主管部门审批，其他专用章（包括经济合同章、财务专用章等）。在名称式样上应与单位正式印章有所区别，经本单位领导批准后可以申请。',
      },
      {
        id: 'sealName',
        label: '原印章名称',
        labelWidth: formLabelWidth8,
        content: '',
      },
      {
        id: 'sealUseTypeName',
        label: '用章方式',
        labelWidth: formLabelWidth3,
        content: '',
        tips:
          '选择Ukey签章需要硬件介质UKey盖章，选择云签章可用于开放服务使用API调用。',
      },
      {
        id: 'newSealName',
        label: '新印章名称',
        type: 'input',
        labelWidth: formLabelWidth8,
        content: '',
      },
    ],
  },
]

const auditOrgDetail = [
  {
    title: '上级审批机构',
    child: [
      {
        id: 'confirmOrganizeName',
        label: '机构名称',
        labelWidth: formLabelWidth3,
        content: '',
      },
      {
        id: 'confirmOrganizeLicenseType',
        label: '证照类型',
        labelWidth: formLabelWidth8,
        content: '',
      },
      {
        id: 'confirmOrganizeLicenseNumber',
        label: '证照号码',
        labelWidth: formLabelWidth3,
        content: '',
      },
    ],
  },
]

const formLabelWidth1: string = '50px'

@Component({})
export default class UpdateSeal extends Vue {
  @Prop({ default: '变更印章详情' }) private title!: string
  // @Prop({}) private data!: any;
  @Prop({ default: false }) private visible!: boolean
  @Prop({ default: true }) private showTimeline!: boolean
  @Prop({ default: {} }) private defaultData!: any
  @Prop({}) private sealOption!: any[]
  @Prop({ default: false }) private isDetail!: boolean
  @Prop({ default: '' }) private uploadUrl!: string
  @Prop({ default: false }) private saveLoading!: boolean
  @Prop({}) private queryAuditOrg!: (e: any) => {}
  @Prop({}) private auditOrgList!: any[]
  private sealUrl = ''
  private detailData: any[] = []
  private sealData: any = {
    newSealName: '',
    auditOrganizeUUID: '',
    auditOrganizeLicenseType: null,
    auditOrganizeLicenseNumber: '',
  }
  private imgVisible = false
  private validImageError = false
  private sealRules = {
    newSealName: [
      { required: true, message: '请输入新印章名称', trigger: 'change' },
      { validator: this.validateSealName, trigger: 'change' },
      { max: 50, message: '印章名称长度不能超过50个字符', trigger: 'change' },
    ],
    auditOrganizeUUID: [
      {
        required: true,
        message: '请输入匹配上级审批机构名称',
        trigger: 'change',
      },
    ],
    auditOrganizeLicenseType: [
      { required: true, message: '证照类型不能为空', trigger: 'change' },
    ],
    auditOrganizeLicenseNumber: [
      { required: true, message: '证照号码不能为空', trigger: 'change' },
    ],
  }

  private file: any = {
    status: 'init',
  }

  protected render(h: any) {
    return (
      <div class={styles.sealDetail}>
        <el-dialog
          title={this.title}
          custom-class="custom-dialog"
          width={'700px'}
          close-on-click-modal={false}
          close-on-press-escape={false}
          visible={this.visible}
          {...{
            on: { 'update:visible': this.visibleChange },
          }}
        >
          <el-form
            class={styles.sealForm}
            hide-required-asterisk
            {...{ props: { model: this.sealData, rules: this.sealRules } }}
            ref="sealForm"
          >
            {this.detailData &&
              this.detailData.map((item: any, index: number) => (
                <DetailItem
                  class={styles.detailItem}
                  data={item.child}
                  v-model={this.sealData}
                  title={item.title}
                />
              ))}
            {!this.isDetail && (
              <div class={sealStyle.formPart}>
                <p class={styles.panel}>
                  <span class={styles.required}>*</span>上级审批机构
                </p>
                <el-row gutter={22}>
                  <el-col span={12}>
                    <el-form-item
                      label="机构名称"
                      label-width={formLabelWidth1}
                      ref="auditOrg"
                      prop="auditOrganizeUUID"
                    >
                      {/* <el-input v-model={this.sealData.auditOrganizeName} autocomplete="off" /> */}
                      <el-select
                        v-model={this.sealData.auditOrganizeUUID}
                        // filterable
                        // remote
                        placeholder="请选择上级审批机构"
                        // remote-method={this.queryAuditOrg}
                        onChange={this.selectAuditOrg}
                        disabled={
                          this.defaultData && this.defaultData.sealType !== 1
                        }
                        // loading="loading"
                      >
                        {this.auditOrgList &&
                          this.auditOrgList.map((org: any, i: number) => (
                            <el-option
                              label={org.organizeName}
                              value={org.organizeUUID}
                            />
                          ))}
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col span={12}>
                    <el-form-item
                      label="证照类型"
                      label-width={formLabelWidth8}
                      prop="auditOrganizeLicenseType"
                      ref="auditOrganizeLicenseType"
                    >
                      <el-select
                        v-model={this.sealData.auditOrganizeLicenseType}
                        disabled
                        placeholder=""
                      >
                        {orgLicenseTypes.map(
                          (orgType: IStatus, index: number) => (
                            <el-option
                              label={orgType.value}
                              value={orgType.id}
                            />
                          )
                        )}
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col span={12}>
                    <el-form-item
                      label="证照号码"
                      label-width={formLabelWidth1}
                      prop="auditOrganizeLicenseNumber"
                      ref="auditOrganizeLicenseNumber"
                    >
                      <el-input
                        v-model={this.sealData.auditOrganizeLicenseNumber}
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                  <el-col span={12} />
                </el-row>
              </div>
            )}
            {!this.isDetail && (
              <div class={sealStyle.splice}>
                <el-button onClick={this.createApplyForm}>
                  <img src={require('@/assets/create-form.png')} />
                  生成印章申请表
                </el-button>
              </div>
            )}
            <p class={styles.panel}>印章申请表</p>
            {this.isDetail &&
              this.defaultData &&
              this.defaultData.sealApplyFileUrl && (
                <div class="thumbnail" onClick={this.preview}>
                  <div class="hover-blank">
                    <img src={require('@/assets/preview.png')} />
                  </div>
                  <img src={this.defaultData.sealApplyFileUrl} />
                </div>
              )}
            {!this.isDetail && (
              <div class={sealStyle.uploadContent}>
                <Upload
                  file={this.file}
                  progress={this.fileProgress}
                  action={this.uploadUrl}
                  success={this.uploadSuccess}
                  error={this.uploadError}
                  preview={this.preview}
                  content="上传印章申请表"
                  beforeUpload={this.beforeUpload}
                />
                <div class={sealStyle.tips}>
                  上传须知:
                  <br /> 1、图片按照A4纸大小扫描，像素300dpi <br />
                  2、格式须为PNG/JPG/BMP/JPEG/GIF
                  <br />
                  3、再次确认申请表中的印模、签字、盖章等重要信息清晰可辨
                </div>
                <p
                  class={{
                    [sealStyle.validError]: true,
                    [sealStyle.error]:
                      this.validImageError && !this.sealData.fileKey,
                  }}
                >
                  请上传印章申请表
                </p>
              </div>
            )}
            {this.showTimeline &&
              this.defaultData &&
              this.defaultData.sealApplyStatus !== 1 && (
                <OptionLine
                  class={styles.optionLine}
                  sealOption={this.sealOption}
                />
              )}
          </el-form>
          {!this.isDetail ? (
            <div slot="footer">
              <el-button
                disabled={this.saveLoading}
                onClick={() => {
                  this.save(false)
                }}
              >
                仅保存
              </el-button>
              <el-button
                type="primary"
                class={[
                  {
                    'btn-primary': true,
                    'btn-primary-hover': this.validField(),
                  },
                ]}
                disabled={this.saveLoading}
                onClick={() => {
                  this.save(true)
                }}
              >
                保存并提交审核
              </el-button>
            </div>
          ) : (
            <div slot="footer">
              <el-button
                onClick={() => {
                  this.$emit('visibleChange', false)
                }}
              >
                关闭
              </el-button>
            </div>
          )}
        </el-dialog>
        <ImagePreview
          visible={this.imgVisible}
          title="申请表预览"
          url={
            this.isDetail ? this.defaultData.sealApplyFileUrl : this.file.url
          }
          onVisibleChange={(val: boolean) => {
            this.imgVisible = val
          }}
        />
      </div>
    )
  }

  private save(isSubmit: boolean) {
    ;(this.$refs.sealForm as ElForm).validate((valid: boolean) => {
      if (isSubmit && !this.sealData.fileKey) {
        // 提交并
        this.validImageError = true
      } else {
        this.validImageError = false
        if (valid) {
          if (isSubmit) {
            this.$emit('saveAndSubmit', this.sealData)
          } else {
            this.$emit('save', this.sealData)
          }
        }
      }
    })
  }

  private preview() {
    this.imgVisible = true
  }
  private validateSealName(
    rule: any,
    value: string,
    callback: (e?: any) => {}
  ) {
    if (value.trim() === '') {
      callback(new Error('请输入新印章名称'))
    } else if (value === this.sealData.sealName) {
      callback(new Error('新印章名称不能与原印章名称相同'))
    } else if (/[!@#$%^&*!！@￥……]/gi.test(value)) {
      callback(new Error('印章名称不能包含特殊字符'))
    } else {
      callback()
    }
  }

  @Emit('visibleChange')
  private visibleChange(val: boolean) {
    return val
  }

  @Watch('visible')
  private visibleHandler(val: boolean) {
    this.validImageError = false
    if (val) {
      const details = detailData.concat(this.isDetail ? auditOrgDetail : [])
      details.forEach((detail: any) => {
        detail.child.forEach((item: any) => {
          item.content = this.defaultData[item.id]
          if (item.id === 'newSealName') {
            item.type = this.isDetail ? 'text' : 'input'
          }
        })
      })
      this.detailData = details
      this.sealData = Object.assign({}, this.defaultData)
      this.$nextTick(() => {
        this.$refs.sealForm && (this.$refs.sealForm as ElForm).clearValidate()
      })
      !this.isDetail &&
        this.queryAuditOrg(
          this.sealData.organizeUUID || this.sealData.applyOrganizeUuid
        )
      if (!!this.sealData.fileKey) {
        this.file = Object.assign(
          {},
          {
            name: '印章申请表',
            status: 'done',
            size: 0,
            url: this.sealData.url,
          }
        )
      } else {
        this.file = {}
      }
    }
  }

  private fileProgress(event: any, file: any, fileList: any[]) {
    this.file = Object.assign(
      {},
      {
        name: file.name,
        status: 'upload',
        size: file.size,
        precent: parseInt(file.percentage),
      }
    )
  }

  private uploadSuccess(response: any, file: any, fileList: any[]) {
    if (response.errCode === 0) {
      this.file = Object.assign(
        {},
        {
          name: file.name,
          status: 'done',
          size: file.size,
          url: URL.createObjectURL(file.raw),
        }
      )
      this.sealData.fileKey = response.data.fileKey
    } else {
      this.file = {}
      this.sealData.fileKey = ''
      this.sealData.url = ''
      this.$message.error(response.msg)
    }
  }

  private validField() {
    return (
      !!this.sealData.agentLicenseType &&
      !!this.sealData.agentName &&
      !!this.sealData.agentLicenseNumber &&
      !!this.sealData.agentMobile &&
      ((this.sealData.reasonType === 4 && !!this.sealData.reason) ||
        this.sealData.reasonType !== 4)
    )
  }

  private uploadError(err: any, file: any, fileList: any[]) {
    this.file = {}
    this.sealData.fileKey = ''
    this.sealData.url = ''
    this.$message.error('文件上传失败')
  }

  private beforeUpload(file: any) {
    const isJPG =
      fileTypes.filter(
        (item: string) => item === (file.type || '').toLowerCase()
      ).length > 0
    const isLimit = file.size / 1024 / 1024 < fileSizeLimit
    if (!isJPG) {
      this.$message.error('申请表只能是 JPG/PNG/BMP/JPEG 格式。')

      return false
    }
    if (!isLimit) {
      this.$message.error(`申请表大小不能超过${fileSizeLimit}MB。`)

      return false
    }
    this.file = Object.assign(
      {},
      { name: file.name, status: 'upload', size: file.size, precent: 0 }
    )
  }

  private createApplyForm() {
    ;(this.$refs.sealForm as ElForm).validate((valid: boolean) => {
      if (valid) {
        this.$emit('createForm', this.sealData)
      }
    })
  }

  private selectAuditOrg(val: string) {
    const org: any[] = this.auditOrgList.filter(
      (item: any) => item.organizeUUID === val
    )
    if (org && org.length > 0) {
      this.sealData = Object.assign(this.sealData, {
        auditOrganizeLicenseNumber: org[0].organizeLicenseNumber,
        auditOrganizeLicenseType: org[0].organizeLicenseType,
        auditOrganizeName: org[0].organizeName,
      })
    }
  }
}
